<?php

namespace video;

use app\commons\model\ActivityVideo;
use app\commons\model\CreateVideo;
use app\job\DownloadVideo;
use app\job\UploadFileVideo;
use think\Controller;
use think\Db;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use OSS\OssClient;
use OSS\Core\OssException;
use think\Exception;
use think\facade\Env;
use think\facade\Log;
use think\Queue;
use app\commons\model\Material;

class Alivideo
{
    public static $URL = 'http://oss-cn-shanghai.aliyuncs.com';

    public $sysset;

    public function __construct()
    {
        $this->sysset = get_sysset();
    }

    /**
     * 阿里云上传视频
     * @param $id
     * @throws ClientException
     * @throws OssException
     * @throws ServerException
     */
    public function aliVideoUpload($id)
    {
        //获取需要上传的素材
        $act = new ActivityVideo();
        $videoList = Material::where(['create_video_id'=>$id])->select();
        $addData = [];
        if(!empty($videoList)){
            $accessKeyId = $this->sysset['basic']['ali_keyid'];
            $accessKeySecret = $this->sysset['basic']['ali_keysecret'];
            $endpoint = self::$URL;
            $bucket = $this->sysset['basic']['ali_bucketname'];
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $top = [];
            $lower = [];
            $middle = [];
            foreach ($videoList as $k=>$v){
                //上传视频到云端
                $object = substr($v['path'], strrpos($v['path'], '/') + 1);
                if($v['is_upload_yun'] == 0){
                    switch (substr($object, strrpos($object, '.') + 1)) {
                        case 'mp4':
                            $fileType = 'video';
                            break;
                        case 'mp3':
                            $fileType = 'audio';
                            break;
                        default:
                            $fileType = 'image';
                            break;
                    }
                    $result = $ossClient->uploadFile($bucket, $object, Env::get('root_path').'public'.$v['path']);
                    if (isset($result['oss-request-url'])) {
                            Material::where(['id'=>$v['id']])->update(['dy_file_name' => $object, 'dy_file_url' => $result['oss-request-url'], 'dy_type' => $fileType,'is_upload_yun'=>1]);
//                            $filelist[] = array();
                    }
                }
                if($v['position'] == 0){
                    //片头
                    $top[] = $v['id'];
                }elseif ($v['position'] == 1){
                    //正片
                    $lower[] = $v['id'];
                }elseif ($v['position'] == 2){
                    //片尾
                    $middle[] = $v['id'];
                }
            }
        }
        /**
         * 组装视频数据
         */
        $lower = getSortCartList($lower);
        $videoLists = getArrSet([$top,$lower,$middle]);

        //获取视频素材数据
        $MaterialList = Material::where('id','in',array_merge($top,$lower,$middle))->select();
        $MaterialListArr = [];
        if(!empty($MaterialList)){
            foreach ($MaterialList as $item){
                $MaterialListArr[$item['id']] = $item;
            }
        }
        $createInfo = CreateVideo::where(['id'=>$id])->find();
        AlibabaCloud::accessKeyClient($accessKeyId, $accessKeySecret)->regionId('cn-shanghai')->asDefaultClient();
        if(!empty($videoLists)){
            foreach ($videoLists as $kk=>$vv){
                //整合素材
                $options = ['RegionId' => "cn-shanghai",
                    'Width' => $createInfo['width'] ? $createInfo['width'] : "720",
                    'Height' => $createInfo['heigh'] ? $createInfo['heigh'] : "1280",
                    'Duration' => mt_rand($createInfo['min'] ? $createInfo['min'] : 20, $createInfo['max'] ? $createInfo['max'] : 30),
                    'DurationAdaption' => "false",
                    'Mute' => "false",
                    'Scene' => 'general',
                    'PuzzleEffect' => 'true',
                    'SmartEffect' => "true"
                ];
                //拼接素材
                $sucaiArr = [];
                foreach ($vv as $k => $v) {
                    $arrs = explode(',',$v);
                    foreach ($arrs as $t){
                        if($t){
                            $sucaiArr[] = $t;
                        }
                    }
                }
                if(!empty($sucaiArr)){
                    foreach ($sucaiArr as $kkk=>$sucai){
                        $options['FileList.' . ($kkk + 1) . '.FileName'] = $MaterialListArr[$sucai]['dy_file_name'];
                        $options['FileList.' . ($kkk + 1) . '.FileUrl'] = $MaterialListArr[$sucai]['dy_file_url'];
                        $options['FileList.' . ($kkk + 1) . '.Type'] = $MaterialListArr[$sucai]['dy_type'];
                    }
                }
                //发送合成任务
                $result = AlibabaCloud::rpc()->product('videoenhan')
                    ->version('2020-03-20')
                    ->action('GenerateVideo')
                    ->method('POST')
                    ->host('videoenhan.cn-shanghai.aliyuncs.com')
                    ->options(array('query' => $options))
                    ->request();
                $res = $result->toArray();
                Log::info('剪辑结果：');
                Log::info($res);
                $videoData['request_id'] = $res['RequestId'] ?? '';
                if (isset($res['RequestId'])) {
                    //合成成功，入库保存
                    $addData = [
                        'sale_id'=>$createInfo['sale_id'],
                        'options'=>json_encode($options),
                        'title'=>$createInfo['title'],
                        'request_id'=>$res['RequestId'],
                        'position'=>!empty($sucaiArr) ? implode(',',$sucaiArr) : 0,
                    ];
                    //保存视频入列
                    $actRes = $act->save($addData);
                    if($actRes) Queue::push(DownloadVideo::class,['id'=>$act->id]);
                    $RequestIds[] = $res['RequestId'];
                    //入列执行视频下载任务
                }
                echo '第' . $kk . '个视频剪辑请求结束' . PHP_EOL;

            }
        }
//        if(!empty($addData)){
//
//            $act->saveAll($addData);
//        }

        //计算合成视频规则，根据素材计算生成视频数量，可音频和视频混合合成
        //阿里云视频合成专场风格
//        目前支持的镜头转场风格包括：basic（无）、slow（舒缓）、fast（动感）
//        、normal（自然）、ink（水墨）、glitch（机械故障）、shift（切换）、mosaic（马赛克）
//        、shutter（百叶窗）、zoom（缩放）、mask（遮罩）、brush（笔刷）、wind（风舞）、smog（烟雾）。
        $TransitionStyle = [
            'slow',
            'fast',
            'normal',
            'ink',
            'glitch',
            'shift',
            'mosaic',
            'shutter',
            'mask',
            'brush',
            'wind',
            'smog'
        ];
        //执行成功
        return true;
    }

    /**
     * 阿里云下载视频
     * @throws ClientException
     * @throws ServerException
     */
    public function aliVideoDownload($id)
    {
        $activity_video = pdo_get('activity_video', array('id' => $id));
        if (!$activity_video) return false;
        if ($activity_video['is_download_status'] == 1) return false;
        $accessKeyId = $this->sysset['basic']['ali_keyid'];
        $accessKeySecret = $this->sysset['basic']['ali_keysecret'];
        AlibabaCloud::accessKeyClient($accessKeyId, $accessKeySecret)
            ->regionId('cn-shanghai')
            ->asDefaultClient();
        $result = AlibabaCloud::rpc()->product('videoenhan')
            ->version('2020-03-20')
            ->action('GetAsyncJobResult')
            ->method('POST')
            ->host('videoenhan.cn-shanghai.aliyuncs.com')
            ->options(array('query' => array('RegionId' => "cn-shanghai", 'JobId' => $activity_video['request_id'])))
            ->request()
            ->toArray();
        if ($result['Data']['Status'] == 'PROCESS_SUCCESS') {
            $data = json_decode($result['Data']['Result'], true);
            $videodata = file_get_contents($data['VideoUrl']);
            self::mkdirs('upload/' . date("Ym"));
            $path =  'upload/' . date("Ym") . '/' . md5($data['VideoUrl']) . '.mp4';
            $paths = $path;
            $path = Env::get('root_path') . 'public/'.$path;
            file_put_contents($path, $videodata);
            pdo_update('activity_video', ['is_download_status' => '1','download_time'=>date('Y-m-d H:i:s'),'path'=>$paths,'synthesis_time'=>date('Y-m-d H:i:s'),'status'=>'1','yun_url'=>$data['VideoUrl']], array('id' => $id));
            return true;
        }
        return false;
    }

    /**
     * 创建目录
     * @param $dir
     * @param int $mode
     * @return bool
     */
    public
    function mkdirs($dir, $mode = 0777)
    {
        if (is_dir($dir) || @mkdir($dir, $mode)) return TRUE;
        if (!mkdirs(dirname($dir), $mode)) return FALSE;
        return @mkdir($dir, $mode);
    }

}

